package com.example.demo.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class AutoTestUtils {
    public static EdgeOptions options;
    public static EdgeDriver driver;

    //创建驱动对象
    public static EdgeDriver createDriver() {
        System.setProperty("webdriver.edge.driver", "C:\\Program Files\\Java\\jdk1.8.0_192\\bin\\msedgedriver.exe");
        if (driver == null) {
            options = new EdgeOptions();
            options.addArguments("--remote-allow-origins=*");
            driver = new EdgeDriver(options);
            //创建隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        }
        driver.get("http://127.0.0.1:8080/login.html");
        return driver;
    }

    public static EdgeDriver loginDriver() {
        driver.get("http://127.0.0.1:8080/login.html");
        driver.findElement(By.cssSelector("#username")).sendKeys("admin");
        driver.findElement(By.cssSelector("#password")).sendKeys("123456");
        driver.findElement(By.cssSelector("#verifyCode")).sendKeys("admin");
        driver.findElement(By.cssSelector("#submit")).click();
        return driver;
    }

    public List<String> getTime() {
        // 文件名格式 20240205-144430毫秒
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat sim2 = new SimpleDateFormat("yyyyMMdd");
        String filename = sim1.format(System.currentTimeMillis());
        String dirname = sim2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return list;
    }

    /**
     * 获取屏幕截图
     */
    public void getScreenShor(String str) throws IOException {
        List<String> list = getTime();
        //dir+filename
        // ./指的是当前项目路径下
        // ./src/test/java/com/example/dirname/filename
        // ./src/test/java/com/example/20240205/20240205-144430毫秒.png
        String filename = "./src/test/java/com/example/" + list.get(0) + "/" + str + "_" + list.get(1) + ".png";
        File srcfile = driver.getScreenshotAs(OutputType.FILE);
        //把屏幕截图生成的文件放到指定路径
        FileUtils.copyFile(srcfile, new File(filename));
    }
}
